package top.xiaoshuaila.config.security;

import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.Collection;

@Component
public class CustomUrlDecisionManager implements AccessDecisionManager {
    @Override
    public void decide(Authentication authentication, Object o, Collection<ConfigAttribute> collection) throws AccessDeniedException, InsufficientAuthenticationException {
        //collection为当前url所需要的角色权限集合
        for(ConfigAttribute configAttribute:collection)
        {
            //当前角色
            String neeRole= configAttribute.getAttribute();
            //如果当前路径允许通过ROLE_LOGIN且登录了就通过,因为未登录的用户也会授予ROLE_LOGIN
            if("ROLE_LOGIN".equals(neeRole))
            {
                //先判断是不是没有登录,如果没有登录就抛异常
                if(authentication instanceof AnonymousAuthenticationToken){
                    throw new AccessDeniedException("尚未登录,请登录");
                }
                else return;
            }
            Collection<? extends GrantedAuthority>authorities= authentication.getAuthorities();
            for(GrantedAuthority authority:authorities){
                if(authority.getAuthority().equals(neeRole))
                    return;
            }
        }
        throw new AccessDeniedException("权限不足,请联系管理员");
    }

    @Override
    public boolean supports(ConfigAttribute configAttribute) {
        return false;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return false;
    }
}
